package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.shuqi.activity.adapter.ProjectDetailsAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.SqImageManager;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.ProjectDetailsController;
import com.shuqi.controller.R;
import com.shuqi.database.model.BookInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.ProjectDetailsInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 专题详情Activity
 * 
 * @author zhuchen
 * 
 */
public class ProjectDetailsActivity extends ActivityBase implements IEventListener,
        HttpRequestErrListener, OnClickListener {

    private final int INIT = EventTypeConstants.BASE;
    private final int INITSUCCESS = INIT + 1;
    private final int SHOW404 = INITSUCCESS + 1;

    private ImageView act_projectdetails_project_image;
    private ProjectDetailsAdapter adapter;
    private ProjectDetailsInfo projectDetailsInfo = null;
    private ListView act_projectdetails_list;
    private List<BookInfo> list = new ArrayList<BookInfo>();
    private int pageIndex = 1;// 请求页
    private LinearLayout layoutLoading;// 进度圈
    private LinearLayout line_404;// 无网络
    private TextView retry;// 重试按钮
    private ProjectDetailsController controller;
    private String topicId;
    private TextView act_projectdetails_intro_text;// 简介
    private CommonTitle mTitle;
    private ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case SHOW404:
                    layoutLoading.setVisibility(View.GONE);
                    line_404.setVisibility(View.VISIBLE);
                    showMsg("网络异常...");
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (controller == null) {
            controller =
                    (ProjectDetailsController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_PROJECTDETAILS, this);
        }
        controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_projectdetails);
        topicId = getIntent().getStringExtra("topicId");
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                this.pageIndex++;
                projectDetailsInfo = (ProjectDetailsInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            default:
                handler.sendEmptyMessage(SHOW404);
                break;
        }

    }

    /**
     * 初始化
     */
    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        this.layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        this.act_projectdetails_list = (ListView) findViewById(R.id.act_projectdetails_list);
        View headView = View.inflate(this, R.layout.act_projectdetails_head, null);
        this.act_projectdetails_project_image =
                (ImageView) headView.findViewById(R.id.act_projectdetails_project_image);
        this.act_projectdetails_intro_text =
                (TextView) headView.findViewById(R.id.act_projectdetails_intro_text);
        this.retry = (TextView) findViewById(R.id.retry);
        this.act_projectdetails_list.addHeaderView(headView);
        this.line_404 = (LinearLayout) findViewById(R.id.include_error);
        mTitle.setTitle(getIntent().getStringExtra("topicName"));
        String url = getIntent().getStringExtra("imgUrl");
        this.asyncLoadImg(act_projectdetails_project_image, url);
        this.retry.setOnClickListener(this);
        controller.handle(0, topicId, pageIndex);
        this.layoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        line_404.setVisibility(View.GONE);
        this.layoutLoading.setVisibility(View.GONE);
        if (projectDetailsInfo != null) {
            if (projectDetailsInfo.getList() != null && projectDetailsInfo.getList().size() > 0) {
                list.addAll(projectDetailsInfo.getList());
                if (adapter == null) {
                    adapter = new ProjectDetailsAdapter(this);
                    adapter.setDataList(list);
                    act_projectdetails_list.setAdapter(adapter);

                } else {
                    adapter.setDataList(list);
                    adapter.notifyDataSetChanged();
                }
            }
            act_projectdetails_intro_text.setText(projectDetailsInfo.getTopicDes());
        }

        act_projectdetails_list.setOnItemClickListener(new myOnItemClickListener());
    }

    /** 列表点击事件 */
    private class myOnItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0) {
                return;
            } else {
                BookInfo bookInfo = list.get(position - 1);
                // 总状态为开
                if ("N".equals(bookInfo.getBookHideState())) {
                    // 封面页开
                    if (1 == bookInfo.getCoverHideState()) {
                        BookCoverActivity.openBookCover(ProjectDetailsActivity.this,
                                bookInfo.getBookId());
                    } else {
                        // 封面关
                        showMsg(getString(R.string.error_bookswitch_coverisclose));
                    }
                } else {
                    // 总状态位关
                    showMsg(getString(R.string.error_bookswitch_ishide));
                }
            }
        }

    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                controller.handle(0, topicId, pageIndex);
//                layoutLoading.setVisibility(View.VISIBLE);
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        controller.handle(0, topicId, pageIndex);
                        layoutLoading.setVisibility(View.VISIBLE);

                    }
                });
                break;
            default:
                break;
        }
    }

    /** 异步加载书旗图片 */
    private void asyncLoadImg(final ImageView iv, String url) {
        SqImageManager.getImageManager().displayImage(url, iv, SqImageManager.IMG_DEFAULT,
                R.drawable.icon_def_bookimg_list);
    }


    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
